// 全局变量
let currentUser = null;
let authToken = null;
let currentRecordId = null;  // 当前记录ID，用于AI问答
let currentAnalysisMarkdown = ''; // 当前AI分析的原始Markdown

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化选择器
    initializeSelectors();
    
    // 初始化城市选择器
    initializeCitySelectors();
    
    // 检查是否有保存的登录状态
    const savedToken = localStorage.getItem('authToken');
    if (savedToken) {
        authToken = savedToken;
        // 验证 token 是否有效
        validateToken();
    }
});

// 初始化选择器
function initializeSelectors() {
    // 初始化年份选择器
    initializeYearSelector();
    
    // 初始化日期选择器
    initializeDaySelector();
    
    // 初始化分钟选择器
    initializeMinuteSelector();
    
    // 添加月份和年份变化监听器
    document.getElementById('birth-month').addEventListener('change', updateDaySelector);
    document.getElementById('birth-year').addEventListener('change', updateDaySelector);
}

// 初始化年份选择器
function initializeYearSelector() {
    const yearSelect = document.getElementById('birth-year');
    const currentYear = new Date().getFullYear();
    
    // 生成1900年到当前年份的选项
    for (let year = currentYear; year >= 1900; year--) {
        const option = document.createElement('option');
        option.value = year;
        option.textContent = year + '年';
        yearSelect.appendChild(option);
    }
}

// 初始化日期选择器
function initializeDaySelector() {
    updateDaySelector();
}

// 更新日期选择器
function updateDaySelector() {
    const yearSelect = document.getElementById('birth-year');
    const monthSelect = document.getElementById('birth-month');
    const daySelect = document.getElementById('birth-day');
    
    // 清空现有选项
    daySelect.innerHTML = '<option value="">请选择日期</option>';
    
    const year = parseInt(yearSelect.value);
    const month = parseInt(monthSelect.value);
    
    if (year && month) {
        // 获取该月的天数
        const daysInMonth = new Date(year, month, 0).getDate();
        
        // 生成日期选项
        for (let day = 1; day <= daysInMonth; day++) {
            const option = document.createElement('option');
            option.value = day;
            option.textContent = day + '日';
            daySelect.appendChild(option);
        }
    }
}

// 初始化分钟选择器
function initializeMinuteSelector() {
    const minuteSelect = document.getElementById('birth-minute');
    
    // 生成0-59分钟的选项
    for (let minute = 0; minute < 60; minute += 5) {
        const option = document.createElement('option');
        option.value = minute;
        option.textContent = minute.toString().padStart(2, '0') + '分';
        minuteSelect.appendChild(option);
    }
}

// 初始化城市选择器
async function initializeCitySelectors() {
    const provinceSelect = document.getElementById('birth-province');
    const citySelect = document.getElementById('birth-city');
    
    try {
        // 加载省份列表
        const response = await fetch('/provinces');
        if (response.ok) {
            const data = await response.json();
            data.provinces.forEach(province => {
                const option = document.createElement('option');
                option.value = province;
                option.textContent = province;
                provinceSelect.appendChild(option);
            });
        }
    } catch (error) {
        console.error('加载省份列表失败：', error);
    }
    
    // 省份变化时加载城市列表
    provinceSelect.addEventListener('change', async function() {
        const province = this.value;
        citySelect.innerHTML = '<option value="">请选择城市</option>';
        
        if (province) {
            citySelect.disabled = false;
            try {
                const response = await fetch(`/cities/${encodeURIComponent(province)}`);
                if (response.ok) {
                    const data = await response.json();
                    data.cities.forEach(city => {
                        const option = document.createElement('option');
                        option.value = city;
                        option.textContent = city;
                        citySelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('加载城市列表失败：', error);
            }
        } else {
            citySelect.disabled = true;
        }
    });
}

// 显示/隐藏标签页
function showTab(tabName) {
    // 隐藏所有表单
    document.querySelectorAll('.auth-form').forEach(form => {
        form.classList.remove('active');
    });
    
    // 移除所有按钮的 active 类
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // 显示选中的表单
    document.getElementById(tabName + '-form').classList.add('active');
    
    // 激活对应的按钮
    event.target.classList.add('active');
}

// 用户注册
async function register(event) {
    event.preventDefault();
    
    const username = document.getElementById('reg-username').value;
    const email = document.getElementById('reg-email').value;
    const password = document.getElementById('reg-password').value;
    
    try {
        const response = await fetch('/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                email: email,
                password: password
            })
        });
        
        if (response.ok) {
            showMessage('注册成功！请登录。', 'success');
            showTab('login');
        } else {
            const error = await response.json();
            showMessage('注册失败：' + error.detail, 'error');
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试。', 'error');
    }
}

// 用户登录
async function login(event) {
    event.preventDefault();
    
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;
    
    try {
        const formData = new FormData();
        formData.append('username', username);
        formData.append('password', password);
        
        const response = await fetch('/login', {
            method: 'POST',
            body: formData
        });
        
        if (response.ok) {
            const data = await response.json();
            authToken = data.access_token;
            localStorage.setItem('authToken', authToken);
            
            // 获取用户信息
            await getUserInfo();
            showMainApp();
            showMessage('登录成功！', 'success');
        } else {
            const error = await response.json();
            showMessage('登录失败：' + error.detail, 'error');
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试。', 'error');
    }
}

// 获取用户信息
async function getUserInfo() {
    try {
        const response = await fetch('/me', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            currentUser = await response.json();
            document.getElementById('welcome-msg').textContent = `欢迎，${currentUser.username}！`;
        }
    } catch (error) {
        console.error('获取用户信息失败：', error);
    }
}

// 验证 token
async function validateToken() {
    try {
        const response = await fetch('/me', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            currentUser = await response.json();
            document.getElementById('welcome-msg').textContent = `欢迎，${currentUser.username}！`;
            showMainApp();
        } else {
            // Token 无效，清除本地存储
            localStorage.removeItem('authToken');
            authToken = null;
        }
    } catch (error) {
        localStorage.removeItem('authToken');
        authToken = null;
    }
}

// 显示主应用
function showMainApp() {
    document.querySelector('.auth-section').style.display = 'none';
    document.getElementById('main-app').style.display = 'block';
    loadHistory();
}

// 退出登录
function logout() {
    authToken = null;
    currentUser = null;
    localStorage.removeItem('authToken');
    
    document.querySelector('.auth-section').style.display = 'block';
    document.getElementById('main-app').style.display = 'none';
    document.getElementById('result-section').style.display = 'none';
    
    // 重置表单
    document.querySelectorAll('form').forEach(form => form.reset());
}

// 第一阶段：计算生辰八字
async function calculateFortune(event) {
    event.preventDefault();
    
    if (!authToken) {
        showMessage('请先登录！', 'error');
        return;
    }
    
    const name = document.getElementById('name').value.trim() || null;
    const gender = document.getElementById('gender').value || null;
    const birthYear = parseInt(document.getElementById('birth-year').value);
    const birthMonth = parseInt(document.getElementById('birth-month').value);
    const birthDay = parseInt(document.getElementById('birth-day').value);
    const birthHour = parseInt(document.getElementById('birth-hour').value);
    const birthMinute = parseInt(document.getElementById('birth-minute').value);
    const province = document.getElementById('birth-province').value || null;
    const city = document.getElementById('birth-city').value || null;
    
    // 显示加载状态
    showLoading();
    
    try {
        // 第一阶段：计算八字
        const baziResponse = await fetch('/calculate-bazi', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({
                birth_year: birthYear,
                birth_month: birthMonth,
                birth_day: birthDay,
                birth_hour: birthHour,
                birth_minute: birthMinute,
                name: name,
                gender: gender,
                province: province,
                city: city
            })
        });
        
        if (baziResponse.ok) {
            const baziData = await baziResponse.json();
            displayBaziResult(baziData);
            
            // 保存记录（第一阶段）
            const saveResponse = await fetch('/save-fortune-record', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${authToken}`
                },
                body: JSON.stringify({
                    birth_year: birthYear,
                    birth_month: birthMonth,
                    birth_day: birthDay,
                    birth_hour: birthHour,
                    birth_minute: birthMinute,
                    name: name,
                    gender: gender,
                    province: province,
                    city: city
                })
            });
            
            if (saveResponse.ok) {
                const record = await saveResponse.json();
                console.log('保存记录成功，记录ID:', record.id);
                currentRecordId = record.id;  // 保存记录ID用于AI问答
                
                // 显示第二阶段按钮
                const btnAnalyze = document.getElementById('btn-analyze');
                if (btnAnalyze) {
                    console.log('找到按钮元素，准备显示');
                    btnAnalyze.style.display = 'block';
                    btnAnalyze.disabled = false;
                    btnAnalyze.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
                    btnAnalyze.onclick = () => {
                        console.log('点击分析按钮，记录ID:', record.id);
                        analyzeFortune(record.id);
                    };
                    console.log('按钮已显示');
                } else {
                    console.error('找不到按钮元素 btn-analyze');
                    // 尝试创建按钮
                    const resultDiv = document.getElementById('bazi-result');
                    if (resultDiv && resultDiv.parentElement) {
                        const newBtn = document.createElement('button');
                        newBtn.id = 'btn-analyze';
                        newBtn.className = 'btn-secondary';
                        newBtn.style.cssText = 'display: block; margin-top: 20px; width: 100%;';
                        newBtn.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
                        newBtn.onclick = () => analyzeFortune(record.id);
                        resultDiv.parentElement.appendChild(newBtn);
                        console.log('已创建新按钮');
                    }
                }
                
                loadHistory(); // 刷新历史记录
            } else {
                // 保存失败时显示错误
                try {
                    const error = await saveResponse.json();
                    console.error('保存记录失败:', error);
                    showMessage('保存记录失败：' + (error.detail || '未知错误'), 'error');
                } catch (e) {
                    console.error('保存记录失败:', e);
                    showMessage('保存记录失败，请重试', 'error');
                }
            }
        } else {
            const error = await baziResponse.json();
            showMessage('计算失败：' + error.detail, 'error');
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试。', 'error');
    }
}

// 第二阶段：AI分析（流式）
async function analyzeFortune(recordId) {
    if (!authToken) {
        showMessage('请先登录！', 'error');
        return;
    }
    
    const btnAnalyze = document.getElementById('btn-analyze');
    btnAnalyze.disabled = true;
    btnAnalyze.textContent = 'AI 正在分析中...';
    
    const analysisDiv = document.getElementById('ai-analysis');
    analysisDiv.innerHTML = `
        <div class="loading">
            <div class="spinner"></div>
            <p>AI 正在分析您的命理，重点关注婚嫁和事业...</p>
        </div>
    `;
    
    document.getElementById('stage2-result').style.display = 'block';
    
    try {
        const response = await fetch(`/analyze-fortune/${recordId}/stream`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (!response.ok) {
            try {
                const error = await response.json();
                showMessage('分析失败：' + (error.detail || '未知错误'), 'error');
            } catch (e) {
                showMessage('分析失败：HTTP ' + response.status, 'error');
            }
            btnAnalyze.disabled = false;
            btnAnalyze.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
            return;
        }
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let fullContent = '';
        let hasReceivedData = false;
        
        // 清空加载状态，准备显示内容
        analysisDiv.innerHTML = '<div class="analysis-content"></div>';
        const contentDiv = analysisDiv.querySelector('.analysis-content');
        
        try {
            while (true) {
                const { done, value } = await reader.read();
                if (done) {
                    console.log('流式响应结束');
                    // 如果没有收到任何数据，可能是错误
                    if (!hasReceivedData && !fullContent) {
                        console.error('没有收到任何数据');
                        showMessage('AI分析失败，请稍后重试', 'error');
                        btnAnalyze.disabled = false;
                        btnAnalyze.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
                    }
                    break;
                }
                
                buffer += decoder.decode(value, { stream: true });
                const lines = buffer.split('\n');
                buffer = lines.pop() || ''; // 保留最后一个不完整的行
                
                for (const line of lines) {
                    if (line.trim() === '') continue; // 跳过空行
                    
                    if (line.startsWith('data: ')) {
                        try {
                            const jsonStr = line.slice(6).trim();
                            if (!jsonStr) continue; // 跳过空的data行
                            
                            const data = JSON.parse(jsonStr);
                            hasReceivedData = true;
                            
                            if (data.type === 'content' && data.text) {
                                fullContent += data.text;
                                currentAnalysisMarkdown = fullContent;
                                // 实时更新显示，使用优化的Markdown渲染
                                contentDiv.innerHTML = markdownToHtml(fullContent);
                                // 自动滚动到底部
                                contentDiv.scrollTop = contentDiv.scrollHeight;
                            } else if (data.type === 'error') {
                                console.error('收到错误:', data.message);
                                showMessage(data.message || 'AI分析失败', 'error');
                                btnAnalyze.disabled = false;
                                btnAnalyze.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
                                return;
                            } else if (data.type === 'done') {
                                console.log('收到完成信号');
                                currentRecordId = recordId;
                                btnAnalyze.style.display = 'none';
                                loadHistory();
                                return;
                            }
                        } catch (e) {
                            console.error('解析流数据错误:', e, '原始行:', line);
                        }
                    } else {
                        // 如果不是data:开头，可能是错误信息或其他格式
                        console.log('收到非标准格式数据:', line);
                    }
                }
            }
            
            // 如果循环结束但没有收到done信号，显示已有内容
            if (fullContent) {
                console.log('流式响应完成，显示最终内容');
                contentDiv.innerHTML = markdownToHtml(fullContent);
                currentAnalysisMarkdown = fullContent;
                btnAnalyze.style.display = 'none';
                loadHistory();
            }
        } catch (streamError) {
            console.error('读取流式响应错误:', streamError);
            showMessage('读取AI响应时出错：' + streamError.message, 'error');
            btnAnalyze.disabled = false;
            btnAnalyze.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
        }
    } catch (error) {
        showMessage('网络错误，请稍后重试。', 'error');
        btnAnalyze.disabled = false;
        btnAnalyze.textContent = '🎯 第二阶段：AI智能分析（婚嫁、事业）';
    }
}

// 显示八字结果
function displayBaziResult(data) {
    const resultDiv = document.getElementById('bazi-result');
    let solarTimeInfo = '';
    if (data.solar_year && data.solar_month && data.solar_day && data.solar_hour !== undefined) {
        solarTimeInfo = `
            <div style="margin-top: 15px; padding: 10px; background: #e3f2fd; border-radius: 8px; font-size: 0.9em; color: #1976d2;">
                <strong>真太阳时：</strong>${data.solar_year}年${data.solar_month}月${data.solar_day}日${data.solar_hour}时${data.solar_minute || 0}分
            </div>
        `;
    }
    
    resultDiv.innerHTML = `
        <div class="bazi-display">
            <div class="pillar">
                <span class="pillar-label">年柱</span>
                <span class="pillar-value">${data.year_pillar}</span>
            </div>
            <div class="pillar">
                <span class="pillar-label">月柱</span>
                <span class="pillar-value">${data.month_pillar}</span>
            </div>
            <div class="pillar">
                <span class="pillar-label">日柱</span>
                <span class="pillar-value">${data.day_pillar}</span>
            </div>
            <div class="pillar">
                <span class="pillar-label">时柱</span>
                <span class="pillar-value">${data.hour_pillar}</span>
            </div>
        </div>
        <div class="five-elements">
            <h5 style="margin-bottom: 15px; color: #667eea;">五行分布</h5>
            <div class="elements-grid">
                <span class="element">木：${data.five_elements.木}个</span>
                <span class="element">火：${data.five_elements.火}个</span>
                <span class="element">土：${data.five_elements.土}个</span>
                <span class="element">金：${data.five_elements.金}个</span>
                <span class="element">水：${data.five_elements.水}个</span>
            </div>
        </div>
        ${solarTimeInfo}
    `;
    
    document.getElementById('result-section').style.display = 'block';
    document.getElementById('stage1-result').style.display = 'block';
    document.getElementById('stage2-result').style.display = 'none';
}

// 显示 AI 分析
function displayAIAnalysis(analysis) {
    const analysisDiv = document.getElementById('ai-analysis');
    
    // 将 Markdown 转换为 HTML
    const htmlContent = markdownToHtml(analysis);
    
    analysisDiv.innerHTML = `
        <h4>AI 智能分析</h4>
        <div class="analysis-content">${htmlContent}</div>
    `;
    // 保存原始Markdown，供复制/导出使用
    currentAnalysisMarkdown = analysis || '';
}

// Markdown 转 HTML 函数（优化版）
function markdownToHtml(markdown) {
    if (!markdown) return '';
    
    let html = markdown;
    
    // 先过滤掉 ```markdown 这样的代码块标记
    html = html.replace(/```markdown\s*\n?/gi, '');
    html = html.replace(/```\s*$/gm, ''); // 移除行尾的```
    
    // 处理代码块（```code```），但排除markdown标记
    // 先处理markdown代码块标记（完全移除）
    html = html.replace(/```markdown\s*\n?([\s\S]*?)```/gi, '$1');
    // 再处理其他代码块
    html = html.replace(/```(\w+)?\n?([\s\S]*?)```/g, (match, lang, code) => {
        // 如果代码块标记是markdown，直接返回代码内容
        if (lang && lang.toLowerCase() === 'markdown') {
            return code.trim();
        }
        return '<pre><code>' + code.trim() + '</code></pre>';
    });
    
    // 处理行内代码（`code`）
    html = html.replace(/`([^`\n]+)`/g, '<code>$1</code>');
    
    // 处理标题（按顺序处理，从大到小）
    html = html.replace(/^#### (.*$)/gim, '<h4>$1</h4>');
    html = html.replace(/^### (.*$)/gim, '<h3>$1</h3>');
    html = html.replace(/^## (.*$)/gim, '<h2>$1</h2>');
    html = html.replace(/^# (.*$)/gim, '<h1>$1</h1>');
    
    // 处理粗体和斜体（先处理粗斜体，再处理粗体，最后处理斜体）
    html = html.replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>');
    html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
    html = html.replace(/(?<!\*)\*(?!\*)([^*]+?)(?<!\*)\*(?!\*)/g, '<em>$1</em>');
    
    // 处理链接
    html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');
    
    // 处理引用块
    html = html.replace(/^> (.*$)/gim, '<blockquote>$1</blockquote>');
    
    // 处理水平线
    html = html.replace(/^---$/gim, '<hr>');
    
    // 处理表格 - 在段落处理之前进行
    // Markdown表格格式：| 列1 | 列2 |\n|-----|-----|\n| 值1 | 值2 |
    const tablePattern = /((?:\|.+\|\s*\n)(?:\|[\s\-:|]+\|\s*\n)?(?:\|.+\|\s*\n?)+)/g;
    html = html.replace(tablePattern, (match) => {
        const lines = match.trim().split('\n');
        const validLines = [];
        
        for (const line of lines) {
            const trimmed = line.trim();
            // 跳过分隔符行（如 |---|---| 或 |:---|:---:|---:|）
            if (trimmed && /^[\s\-:|]+$/.test(trimmed)) {
                continue;
            }
            // 保留表格数据行
            if (trimmed && trimmed.startsWith('|') && trimmed.endsWith('|')) {
                validLines.push(trimmed);
            }
        }
        
        if (validLines.length === 0) return match;
        
        let tableHtml = '<table>';
        
        // 第一行作为表头
        const headerCells = validLines[0].split('|').filter(cell => cell.trim());
        tableHtml += '<thead><tr>';
        headerCells.forEach(cell => {
            const cellContent = cell.trim();
            // 处理表头中的Markdown格式（粗体、斜体等）
            let processedCell = cellContent
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>');
            tableHtml += '<th>' + processedCell + '</th>';
        });
        tableHtml += '</tr></thead>';
        
        // 其余行作为表体
        if (validLines.length > 1) {
            tableHtml += '<tbody>';
            for (let i = 1; i < validLines.length; i++) {
                const cells = validLines[i].split('|').filter(cell => cell.trim());
                tableHtml += '<tr>';
                cells.forEach(cell => {
                    const cellContent = cell.trim();
                    // 处理单元格中的Markdown格式
                    let processedCell = cellContent
                        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                        .replace(/\*(.*?)\*/g, '<em>$1</em>')
                        .replace(/`([^`]+)`/g, '<code>$1</code>');
                    tableHtml += '<td>' + processedCell + '</td>';
                });
                tableHtml += '</tr>';
            }
            tableHtml += '</tbody>';
        }
        
        tableHtml += '</table>';
        return tableHtml;
    });
    
    // 处理无序列表
    const ulPattern = /(?:^[\*\-] .+(?:\n|$))+/gm;
    html = html.replace(ulPattern, (match) => {
        const items = match.match(/^[\*\-] (.+)$/gm);
        if (items) {
            const listItems = items.map(item => '<li>' + item.replace(/^[\*\-] /, '') + '</li>').join('');
            return '<ul>' + listItems + '</ul>';
        }
        return match;
    });
    
    // 处理有序列表
    const olPattern = /(?:^\d+\. .+(?:\n|$))+/gm;
    html = html.replace(olPattern, (match) => {
        const items = match.match(/^\d+\. (.+)$/gm);
        if (items) {
            const listItems = items.map(item => '<li>' + item.replace(/^\d+\. /, '') + '</li>').join('');
            return '<ol>' + listItems + '</ol>';
        }
        return match;
    });
    
    // 处理段落：将连续的非空行组合成段落
    const lines = html.split('\n');
    const processedLines = [];
    let currentParagraph = [];
    let inPreBlock = false;
    let inList = false;
    
    for (let i = 0; i < lines.length; i++) {
        let line = lines[i];
        const trimmedLine = line.trim();
        
        // 检查是否在代码块中
        if (trimmedLine.includes('<pre>')) {
            inPreBlock = true;
        }
        if (trimmedLine.includes('</pre>')) {
            inPreBlock = false;
        }
        
        // 检查是否在列表中
        if (trimmedLine.match(/^<(ul|ol)/)) {
            inList = true;
        }
        if (trimmedLine.match(/<\/(ul|ol)>/)) {
            inList = false;
        }
        
        // 如果在代码块中，直接添加
        if (inPreBlock || line.includes('<pre>') || line.includes('</pre>')) {
            if (currentParagraph.length > 0) {
                processedLines.push('<p>' + currentParagraph.join(' ') + '</p>');
                currentParagraph = [];
            }
            processedLines.push(line);
            continue;
        }
        
        // 如果是空行，结束当前段落
        if (!trimmedLine) {
            if (currentParagraph.length > 0) {
                processedLines.push('<p>' + currentParagraph.join(' ') + '</p>');
                currentParagraph = [];
            }
            continue;
        }
        
        // 如果是HTML标签（标题、列表、表格、引用等），结束当前段落并添加标签
        if (trimmedLine.match(/^<(h[1-6]|ul|ol|li|blockquote|hr|code|strong|em|a|table|thead|tbody|tr|th|td)/)) {
            if (currentParagraph.length > 0) {
                processedLines.push('<p>' + currentParagraph.join(' ') + '</p>');
                currentParagraph = [];
            }
            processedLines.push(trimmedLine);
            continue;
        }
        
        // 否则添加到当前段落
        // 如果包含HTML标签（如strong, em等），直接添加
        if (trimmedLine.includes('<') && trimmedLine.includes('>')) {
            currentParagraph.push(trimmedLine);
        } else {
            // 纯文本，转义HTML特殊字符
            const escaped = trimmedLine
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
            currentParagraph.push(escaped);
        }
    }
    
    // 处理最后一个段落
    if (currentParagraph.length > 0) {
        processedLines.push('<p>' + currentParagraph.join(' ') + '</p>');
    }
    
    html = processedLines.join('\n');
    
    // 清理多余的空白和空段落
    html = html.replace(/\n{3,}/g, '\n\n');
    html = html.replace(/<p>\s*<\/p>/g, '');
    
    return html;
}

// 一键复制 Markdown
async function copyAnalysisMarkdown() {
    const text = currentAnalysisMarkdown && currentAnalysisMarkdown.trim();
    if (!text) {
        showMessage('暂无可复制的内容', 'error');
        return;
    }
    try {
        const btn = document.getElementById('btn-copy-md');
        if (btn) { btn.disabled = true; btn.textContent = '✅ 已复制'; }
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(text);
        } else {
            // 兼容性回退
            const textarea = document.createElement('textarea');
            textarea.value = text;
            textarea.style.position = 'fixed';
            textarea.style.left = '-9999px';
            document.body.appendChild(textarea);
            textarea.focus();
            textarea.select();
            document.execCommand('copy');
            textarea.remove();
        }
        showMessage('Markdown 已复制到剪贴板', 'success');
        setTimeout(() => {
            if (btn) { btn.disabled = false; btn.textContent = '📋 一键复制 Markdown'; }
        }, 1500);
    } catch (e) {
        showMessage('复制失败，请手动复制', 'error');
        const btn = document.getElementById('btn-copy-md');
        if (btn) { btn.disabled = false; btn.textContent = '📋 一键复制 Markdown'; }
    }
}

// 导出为 PDF（基于当前渲染的 HTML）
async function exportAnalysisPDF() {
    const container = document.getElementById('ai-analysis');
    if (!container || !container.innerText.trim()) {
        showMessage('暂无可导出的内容', 'error');
        return;
    }
    try {
        const btn = document.getElementById('btn-export-pdf');
        if (btn) { btn.disabled = true; btn.textContent = '⏳ 正在导出...'; }
        document.body.classList.add('exporting-pdf');

        // 优先尝试库方式；否则自动降级到浏览器打印为PDF
        try {
            await ensurePdfLibraries();
            if (typeof html2canvas === 'function') {
                const jsPDFCtor = (window.jspdf && window.jspdf.jsPDF) ? window.jspdf.jsPDF : (window.jsPDF || null);
                if (jsPDFCtor) {
                    // 使用 html2canvas 将容器渲染为画布
                    const canvas = await html2canvas(container, {
                        backgroundColor: '#ffffff',
                        scale: 2,
                        useCORS: true
                    });
                    const pdf = new jsPDFCtor('p', 'pt', 'a4');
                    const pageWidth = pdf.internal.pageSize.getWidth();
                    const pageHeight = pdf.internal.pageSize.getHeight();
                    const imgWidth = pageWidth - 60;
                    const ratio = imgWidth / canvas.width;
                    const pageImageHeight = pageHeight - 60;
                    const pageSourceHeight = pageImageHeight / ratio;

                    let remainingHeight = (canvas.height * imgWidth) / canvas.width;
                    let srcY = 0;
                    const pageCanvas = document.createElement('canvas');
                    const pageCtx = pageCanvas.getContext('2d');

                    while (remainingHeight > 0) {
                        pageCanvas.width = canvas.width;
                        pageCanvas.height = Math.min(pageSourceHeight, canvas.height - srcY);
                        pageCtx.clearRect(0, 0, pageCanvas.width, pageCanvas.height);
                        pageCtx.drawImage(canvas, 0, srcY, canvas.width, pageCanvas.height, 0, 0, pageCanvas.width, pageCanvas.height);
                        const pageImg = pageCanvas.toDataURL('image/png');
                        const drawHeight = pageCanvas.height * ratio;
                        pdf.addImage(pageImg, 'PNG', 30, 30, imgWidth, drawHeight);
                        srcY += pageCanvas.height;
                        remainingHeight -= drawHeight;
                        if (remainingHeight > 0) pdf.addPage();
                    }

                    const filename = `AI_分析_${new Date().toISOString().slice(0,19).replace(/[:T]/g,'-')}.pdf`;
                    pdf.save(filename);
                    showMessage('PDF 导出完成', 'success');
                    return;
                }
            }
            // 若库不可用，走打印降级
            await printExport(container);
            showMessage('已打开系统打印对话框，请选择“保存为PDF”', 'info');
        } catch (inner) {
            // 库导出失败，使用打印降级
            await printExport(container);
            showMessage('已打开系统打印对话框，请选择“保存为PDF”', 'info');
        }
    } catch (e) {
        console.error(e);
        showMessage('导出失败：' + (e && e.message ? e.message : '请重试'), 'error');
    } finally {
        document.body.classList.remove('exporting-pdf');
        const btn = document.getElementById('btn-export-pdf');
        if (btn) { btn.disabled = false; btn.textContent = '🧾 导出为 PDF'; }
    }
}

// 动态加载并校验 PDF 依赖
async function ensurePdfLibraries() {
    function loadScript(src) {
        return new Promise((resolve, reject) => {
            // 已存在则直接 resolve
            const exists = Array.from(document.scripts).some(s => s.src && s.src.includes(src));
            if (exists) return resolve();
            const s = document.createElement('script');
            s.src = src;
            s.async = true;
            s.onload = () => resolve();
            s.onerror = () => reject(new Error('脚本加载失败：' + src));
            document.head.appendChild(s);
        });
    }
    // 若未加载则尝试加载
    if (typeof html2canvas !== 'function') {
        await loadScript('https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js');
    }
    if (!(window.jspdf && window.jspdf.jsPDF) && !window.jsPDF) {
        await loadScript('https://cdn.jsdelivr.net/npm/jspdf@2.5.1/dist/jspdf.umd.min.js');
    }
}

// 无依赖降级：通过浏览器打印导出为PDF
async function printExport(container) {
    const html = buildPrintableHtml(container.innerHTML);
    const printWindow = window.open('', '_blank');
    if (!printWindow) throw new Error('弹窗被拦截，请允许弹窗后重试');
    printWindow.document.open();
    printWindow.document.write(html);
    printWindow.document.close();
    // 等待样式与内容渲染
    await new Promise(r => setTimeout(r, 300));
    printWindow.focus();
    printWindow.print();
}

function buildPrintableHtml(inner) {
    const styleReset = `
      <style>
        body { margin: 0; padding: 20px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', 'SimSun', sans-serif; }
        #print-root { max-width: 900px; margin: 0 auto; }
        .analysis-content { max-height: none !important; overflow: visible !important; padding: 0; }
        #ai-analysis { box-shadow: none; }
        @media print {
          body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
          .btn-secondary, .btn-primary { display: none !important; }
        }
      </style>
    `;
    // 同域样式链接，若能加载会提升打印质量
    const linkCss = '<link rel="stylesheet" href="/static/style.css">';
    return `<!DOCTYPE html><html><head><meta charset="utf-8">${linkCss}${styleReset}</head><body><div id="print-root"><div id="ai-analysis"><div class="analysis-content">${inner}</div></div></div></body></html>`;
}

// 显示加载状态
function showLoading() {
    const resultDiv = document.getElementById('bazi-result');
    
    resultDiv.innerHTML = `
        <div class="loading">
            <div class="spinner"></div>
            <p>正在计算生辰八字（使用真太阳时）...</p>
        </div>
    `;
    
    document.getElementById('result-section').style.display = 'block';
    document.getElementById('stage1-result').style.display = 'block';
    document.getElementById('stage2-result').style.display = 'none';
    document.getElementById('btn-analyze').style.display = 'none';
}

// 加载历史记录
async function loadHistory() {
    if (!authToken) return;
    
    try {
        const response = await fetch('/fortune-records', {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const records = await response.json();
            displayHistory(records);
        }
    } catch (error) {
        console.error('加载历史记录失败：', error);
    }
}

// 显示历史记录
function displayHistory(records) {
    const historyList = document.getElementById('history-list');
    
    if (records.length === 0) {
        historyList.innerHTML = '<p class="no-records">暂无历史记录</p>';
        return;
    }
    
    historyList.innerHTML = records.map(record => {
        const nameInfo = record.name ? `<span style="color: #667eea; font-weight: 600;">${record.name}</span>` : '';
        const genderInfo = record.gender ? `<span style="color: #999;">${record.gender}</span>` : '';
        const stageBadge = record.stage === 2 ? '<span style="background: #4caf50; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em; margin-left: 10px;">已分析</span>' : '<span style="background: #ff9800; color: white; padding: 2px 8px; border-radius: 10px; font-size: 0.8em; margin-left: 10px;">仅八字</span>';
        
        return `
            <div class="history-item" onclick="viewRecord(${record.id})">
                <h4>
                    ${nameInfo} ${genderInfo} ${stageBadge}
                </h4>
                <div style="margin-top: 8px; color: #666;">
                    ${record.birth_year}年${record.birth_month}月${record.birth_day}日 ${record.birth_hour}时${record.birth_minute}分
                </div>
                <div class="date">${new Date(record.created_at).toLocaleString('zh-CN')}</div>
                <div class="bazi-info">
                    ${record.year_pillar} ${record.month_pillar} ${record.day_pillar} ${record.hour_pillar}
                </div>
            </div>
        `;
    }).join('');
}

// 查看记录详情
async function viewRecord(recordId) {
    try {
        const response = await fetch(`/fortune-records/${recordId}`, {
            headers: {
                'Authorization': `Bearer ${authToken}`
            }
        });
        
        if (response.ok) {
            const record = await response.json();
            currentRecordId = record.id;
            
            // 计算五行
            const fiveElements = {
                木: 0, 火: 0, 土: 0, 金: 0, 水: 0
            };
            const allPillars = record.year_pillar + record.month_pillar + record.day_pillar + record.hour_pillar;
            // 简化的五行计算（实际应该使用完整计算）
            const elements = {
                '甲': '木', '乙': '木', '丙': '火', '丁': '火', '戊': '土', '己': '土',
                '庚': '金', '辛': '金', '壬': '水', '癸': '水',
                '子': '水', '丑': '土', '寅': '木', '卯': '木', '辰': '土', '巳': '火',
                '午': '火', '未': '土', '申': '金', '酉': '金', '戌': '土', '亥': '水'
            };
            for (let char of allPillars) {
                if (elements[char]) {
                    fiveElements[elements[char]]++;
                }
            }
            
            // 显示八字结果
            const baziData = {
                year_pillar: record.year_pillar,
                month_pillar: record.month_pillar,
                day_pillar: record.day_pillar,
                hour_pillar: record.hour_pillar,
                five_elements: fiveElements,
                solar_year: record.solar_year,
                solar_month: record.solar_month,
                solar_day: record.solar_day,
                solar_hour: record.solar_hour,
                solar_minute: record.solar_minute
            };
            
            displayBaziResult(baziData);
            
            // 如果已有AI分析，显示分析结果
            if (record.stage === 2 && record.ai_analysis) {
                displayAIAnalysis(record.ai_analysis);
                document.getElementById('stage2-result').style.display = 'block';
                document.getElementById('btn-analyze').style.display = 'none';
                // 确保按钮可用
                currentAnalysisMarkdown = record.ai_analysis || '';
            } else {
                // 显示第二阶段按钮
                const btnAnalyze = document.getElementById('btn-analyze');
                btnAnalyze.style.display = 'block';
                btnAnalyze.onclick = () => analyzeFortune(record.id);
                document.getElementById('stage2-result').style.display = 'none';
                currentAnalysisMarkdown = '';
            }
            
            // 滚动到结果区域
            document.getElementById('result-section').scrollIntoView({ behavior: 'smooth' });
        }
    } catch (error) {
        showMessage('加载记录失败', 'error');
    }
}

// AI问答功能（流式）
async function askAIQuestion() {
    if (!currentRecordId) {
        showMessage('请先完成八字计算', 'error');
        return;
    }
    
    const questionInput = document.getElementById('ai-question-input');
    const question = questionInput.value.trim();
    
    if (!question) {
        showMessage('请输入问题', 'error');
        return;
    }
    
    // 显示问题
    const qaQuestions = document.getElementById('qa-questions');
    const questionDiv = document.createElement('div');
    questionDiv.className = 'qa-item';
    questionDiv.innerHTML = `
        <div class="question">${question}</div>
        <div class="answer">正在思考中...</div>
    `;
    qaQuestions.appendChild(questionDiv);
    const answerDiv = questionDiv.querySelector('.answer');
    
    questionInput.value = '';
    
    // 滚动到最新问题
    questionDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    
    try {
        const response = await fetch('/ai-question/stream', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${authToken}`
            },
            body: JSON.stringify({
                record_id: currentRecordId,
                question: question
            })
        });
        
        if (!response.ok) {
            try {
                const error = await response.json();
                answerDiv.innerHTML = `<span style="color: #f5576c;">错误：${error.detail || '未知错误'}</span>`;
            } catch (e) {
                answerDiv.innerHTML = `<span style="color: #f5576c;">错误：HTTP ${response.status}</span>`;
            }
            return;
        }
        
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let fullContent = '';
        
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop();
            
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    try {
                        const data = JSON.parse(line.slice(6));
                        if (data.type === 'content') {
                            fullContent += data.text;
                            // 实时更新显示
                            answerDiv.innerHTML = markdownToHtml(fullContent);
                            // 自动滚动
                            questionDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                        } else if (data.type === 'done') {
                            return;
                        }
                    } catch (e) {
                        console.error('解析流数据错误:', e);
                    }
                }
            }
        }
    } catch (error) {
        answerDiv.innerHTML = `<span style="color: #f5576c;">网络错误，请稍后重试</span>`;
    }
}

// 快速提问
function quickQuestion(question) {
    document.getElementById('ai-question-input').value = question;
    askAIQuestion();
}

// 允许回车键提交问题
document.addEventListener('DOMContentLoaded', function() {
    const questionInput = document.getElementById('ai-question-input');
    if (questionInput) {
        questionInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                askAIQuestion();
            }
        });
    }
});

// 显示消息
function showMessage(message, type = 'info') {
    // 移除现有消息
    const existingMessage = document.querySelector('.message');
    if (existingMessage) {
        existingMessage.remove();
    }
    
    // 创建新消息
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    
    // 插入到页面顶部
    const container = document.querySelector('.container');
    container.insertBefore(messageDiv, container.firstChild);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.remove();
        }
    }, 3000);
}
